package com.laikan.reader.bookreader.util;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.ChapterBean;
import com.laikan.reader.core.bean.ChapterDetailBean;
import com.laikan.reader.core.utils.EncryptUtils;
import com.socks.library.KLog;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 章节目录下载
 * Created by wx on 16/9/2.
 */
public class ChapterDown {

    private List<String> mFileList = new ArrayList<>();//已下载文件数
    private String book_id;  //书id
    private ArrayList<ChapterBean> chapterData = new ArrayList<>();//下载章节目录 去掉卷
    private int chapterIndex = 0; //下载章节目录的下标
    private Context context;
    private int STARTDOWN = 1; //开始下载
    private int DOWNLOADING = 2; //下载中
    private int DownloadCOMPLETE = 3; //下载完成
    private int fileCount = 0; //下载文件数
    private String bookName;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == STARTDOWN) {
                ToastMgr.showShortToast(R.string.chapter_down_start);
            }else if (msg.what == DOWNLOADING) {
                ToastMgr.showShortToast(R.string.chapter_down_ing);
            }else if (msg.what == DownloadCOMPLETE) {
                ToastMgr.showShortToast("《"+bookName+"》" + context.getResources().getString(R.string.chapter_down_complete));
            }
        }
    };

    /**
     * 构造
     *
     * @param context
     * @param bookid
     * @param chapterData
     */
    public ChapterDown(Context context, String bookid, String bookName, ArrayList<ChapterBean> chapterData) {
        chapterIndex = 0;
        this.book_id = bookid;
        this.bookName = bookName;
        this.chapterData = chapterData;
        this.context = context;
        File f = new File(ChapterUtil.getBookPath(book_id));
        mFileList = getFile(f);
    }

    /**
     * 章节下载
     */
    public synchronized void downloadChapter() {
        if(chapterIndex < chapterData.size()){
            if (mFileList.contains(chapterData.get(chapterIndex).getId())) {
                chapterIndex++;
                downloadChapter();
            }else {
                Map<String, String> map = new HashMap<>();
                map.put("sd", SPUtil.getString("token", ""));
                RequestListener requestListener = new RequestListener() {
                    @Override
                    public void onPreExecute() {
                        KLog.e("---------volley onPreExecute!!!");
                    }

                    @Override
                    public void onSuccess(final HttpResponse httpResponse) {
                        final BaseDataBean<ChapterDetailBean> result;
                        Gson gson = new Gson();
                        Type type = new TypeToken<BaseDataBean<ChapterDetailBean>>() {}.getType();
                        try {
                            result = gson.fromJson(httpResponse.responseContent, type);
                            if (result.getResult().equals("1")) {
                                if (!result.getError_no().equals("600")) {
                                    fileCount++;
                                    new Thread(){
                                        @Override
                                        public void run() {
                                            saveChapterFile(result.getData().getId(), httpResponse.responseContent);
                                        }
                                    }.start();

                                    chapterIndex++;
                                    downloadChapter();
                                }else {
                                    //非正常情况下导致下次不能下载
                                    SPUtil.putBoolean(book_id + "isDowning_chapter", true);
                                    handler.sendEmptyMessage(DownloadCOMPLETE);
                                    //ToastMgr.showShortToast("《"+bookName+"》" + context.getResources().getString(R.string.chapter_down_complete));
                                    return;
                                }
                                //防止数组越界导致下次不能下载
                                if (chapterIndex == chapterData.size()) {
                                    SPUtil.putBoolean(book_id + "isDowning_chapter", true);
                                    handler.sendEmptyMessage(DownloadCOMPLETE);
                                    //ToastMgr.showShortToast("《"+bookName+"》" + context.getResources().getString(R.string.chapter_down_complete));
                                }
                            }else {
                                //下载完成
                                handler.sendEmptyMessage(DownloadCOMPLETE);
                                //ToastMgr.showShortToast("《"+bookName+"》" + context.getResources().getString(R.string.chapter_down_complete));
                                SPUtil.putBoolean(book_id + "isDowning_chapter", true);
                            }
                        }catch (JsonSyntaxException e) {
                            //防止解析错误导致下次不能下载
                            SPUtil.putBoolean(book_id + "isDowning_chapter", true);
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(VolleyErrorHandler errorHandler) {
                        SPUtil.putBoolean(book_id + "isDowning_chapter", true);
                    }

                    @Override
                    public void onFinish() {

                    }
                };

                Requester requester = new Requester();
                requester.setUrl(APIProtocol.laikan_book_detail + book_id + "_" + chapterData.get(chapterIndex).getId());
                requester.setMapBody(map);
                HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//                HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_book_detail + book_id + "_" + chapterData.get(chapterIndex).getId(), map, null, null,requestListener);
            }
        }else{
            SPUtil.putBoolean(book_id + "isDowning_chapter", true);
            handler.sendEmptyMessage(DownloadCOMPLETE);
        }

    }

    /**
     * 保存章节
     *
     * @param chapterid
     * @param json
     */
    private synchronized void saveChapterFile(final String chapterid, String json) {
        File file = new File(ChapterUtil.getChapterPath_BookId(book_id,chapterid));
        if (!file.isDirectory()) {
            file.delete();
            file.mkdirs();
        }
        if (!file.exists()) {
            file.mkdirs();
        }
        EncryptUtils.encrypt(new File(file.getPath()), ChapterUtil.EFS_KEY, json);
        Intent intent = new Intent(book_id + Constants.CHAPTER_DOWN_BROADCAST);
        intent.putExtra("progress", fileCount);
        context.sendBroadcast(intent);
    }

    /**
     * 获取已下载章节id
     */
    public List<String> getFile(File file) {
        List<String> mFileList = new ArrayList<String>();
        File[] fileArray = file.listFiles();
        try {
            for (File f : fileArray) {
                if (f.isFile()) {
                    mFileList.add(f.getName());
                }else {
                    getFile(f);
                }
            }
        }catch (Exception e) {
            // TODO: handle exception
        }

        return mFileList;
    }
}
